package com.scape.core.web;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.scape.core.model.Resource;

@RooWebScaffold(path = "resources", formBackingObject = Resource.class , exposeJson=true)
@RequestMapping("/resources")
@Controller
public class ResourceController 
{
	/*
	@RequestMapping(value="/childResources", method=RequestMethod.GET)
	public @ResponseBody String getChildResources(@RequestParam Long parentResourceId) 
	{
		Resource parentResource = Resource.findResource(parentResourceId);
		TypedQuery<Resource> typedQuery = (TypedQuery<Resource>) Resource.findResourcesByParentResource(parentResource);
		if (isNotEmpty(typedQuery.getResultList()))			
		{
			return Resource.toJsonArray(typedQuery.getResultList());
		}
		return Resource.toJsonArray(null);
	}
*/
	@RequestMapping(value="/createCategoryFromJson" , method = RequestMethod.POST, headers = "Accept=application/json")
	public @ResponseBody String createCategoryFromJson(@RequestBody String json) {
	        Resource rr =  Resource.fromJsonToResource(json);
	        rr.setIsCategory(Boolean.TRUE);
	        rr.persist();
	        return rr.toJson();
	}
	
	
	@RequestMapping(value="/createItemFromJson" , method = RequestMethod.POST, headers = "Accept=application/json")
	public ResponseEntity<String> createItemFromJson(@RequestBody String json) {
	        Resource rr =  Resource.fromJsonToResource(json);
	        rr.setParentResource(Resource.findResource(rr.getParentResource().getId()));
	        rr.setIsCategory(Boolean.FALSE);
	        rr.persist();
	        HttpHeaders headers= new HttpHeaders();
	        headers.add("Content-Type", "application/json");
	        return new ResponseEntity<String>(headers, HttpStatus.CREATED);
	}
	  
	@RequestMapping(value="/updateFromJson" , method = RequestMethod.PUT, headers = "Accept=application/json")
    public ResponseEntity<String> updateFromJson(@RequestBody String json) {
        HttpHeaders headers= new HttpHeaders();
        headers.add("Content-Type", "application/text");
        Resource rr = Resource.fromJsonToResource(json);
        if (rr == null || rr.getId() == null) {
            return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
        }
        Resource res = Resource.findResource(rr.getId());
		res.setTitle(rr.getTitle());
		res.setDescription(rr.getDescription());
		res.merge();
        return new ResponseEntity<String>(headers, HttpStatus.OK);
    }
	
	@RequestMapping(value="/topLevelResources", method=RequestMethod.GET)
	public @ResponseBody String getTopLevelResources() 
	{
		TypedQuery<Resource> typedQuery = (TypedQuery<Resource>) Resource.findTopLevelResources();
		if (isNotEmpty(typedQuery.getResultList()))			
		{
			return Resource.toJsonArray(typedQuery.getResultList());
		}
		return Resource.toJsonArray(null);
	}

	
	private boolean isNotEmpty(List<Resource> list)
    {
    	if ((list==null) || list.isEmpty())
    		return false;
    	
    	return true;
    }
	
	
	@RequestMapping(method = RequestMethod.PUT)
    public String update(@Valid Resource resource, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("resource", resource);
            return "resources/update";
        }
        uiModel.asMap().clear();
        if(resource.getId() != null)
        resource.merge();
        return "redirect:/resources/" + encodeUrlPathSegment(resource.getId().toString(), httpServletRequest);
    }

	@RequestMapping(method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            uiModel.addAttribute("resources", Resource.findTopLevelResources(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo).getResultList());
            float nrOfPages = (float) Resource.countResources() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("resources", Resource.findTopLevelResources().getResultList());
        }
        return "resources/list";
    }
	
	
}
